package photorganizer.common.bean;

import java.util.HashMap;
import java.util.Map;

public class CacheLocator extends LocatorAbstract {

	private final Map<Class<?>, Object> beans;

	public CacheLocator(Locator delegate) {
		super(delegate);
		beans = new HashMap<Class<?>, Object>();
	}

	@Override
	public <T> T get(Class<T> beanClass) {
		if (beans.containsKey(beanClass)) {
			Object result = beans.get(beanClass);
			return beanClass.cast(result);
		}

		return load(beanClass);
	}

	private synchronized <T> T load(Class<T> beanClass) {
		if (beans.containsKey(beanClass)) {
			Object result = beans.get(beanClass);
			return beanClass.cast(result);
		}

		T result = super.get(beanClass);
		beans.put(beanClass, result);
		return result;
	}

}
